package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuPrice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements ICartService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RemoteProductService remoteProductService;

    private String getCartKey(Long userId) {
        //定义key user:userId:cart
        return "user:cart:" + userId;
    }

    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        //1，准备RedisHash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey =getCartKey(userId);

        //2.准备Redis Hash类型的 hashKey
        String hashKey = skuId.toString();

        //3.准备CartInfo
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);

        int threshold = 99;  //单品数量限制

        if (hashOperations.hasKey(hashKey)) { //在做修改
            CartInfo cartInfo = hashOperations.get(hashKey);
            int totalNum = cartInfo.getSkuNum() + skuNum;
            cartInfo.setSkuNum(totalNum > threshold ? threshold : totalNum);
            cartInfo.setUpdateTime(new Date());

            hashOperations.put(hashKey, cartInfo);
    }else { //不在做添加
            Long size = hashOperations.size(); //不同商品数量，上线50

            if(size>=50){
                throw new ServiceException("商品数量不能超过50件");
            }

            CartInfo cartInfo = new CartInfo();
            cartInfo.setCreateTime(new Date());
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuNum(skuNum); //默认1

            //远程调用商品微服务，根据skuId查询ProductSku对象
            R<ProductSku> productSkuR = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (productSkuR.getCode() == R.FAIL) { //判断远程接口调用是否降级处理了。
                throw new ServiceException(productSkuR.getMsg());
            }
            ProductSku productSku = productSkuR.getData();
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());

            hashOperations.put(hashKey, cartInfo);
        }
}

    @Override
    public List<CartInfo> cartList() {
        //1.准备Redis Hash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey =  getCartKey(userId);

        BoundHashOperations<String,String,CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOperations.values(); //从redis中获取数据旧价格数据

        //2.更新商品实时价格(注意：只需要更新JVM堆内存对象的商品最新价格，redis中数据不变)
        //2.1 批量获取商品最新价格。
        if(!CollectionUtils.isEmpty(cartInfoList)){
            List<Long> skuIdList = cartInfoList.stream().map((cartInfo) -> cartInfo.getSkuId()).toList();
            R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
            if(R.FAIL == skuPriceListR.getCode()){
                throw new ServiceException(skuPriceListR.getMsg());
            }
            List<SkuPrice> skuPriceList = skuPriceListR.getData(); //数据库最新价格

            //为了从集合skuPriceList中找数据方便，我们需要转Map
            Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream()
                    .collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

            //2.2更新每个实时价格
            for (CartInfo cartInfo : cartInfoList) {
                /*skuPriceList.stream().filter((skuPrice)->{
                    return skuPrice.getSkuId().equals(cartInfo.getSkuId())
                }).findFirst().ifPresent((skuPrice)->{
                    cartInfo.setSkuPrice(skuPrice.getSalePrice());
                });*/
                cartInfo.setSkuPrice(skuIdToSalePriceMap.get(cartInfo.getSkuId()));
            }

            return cartInfoList;
        }


        return new ArrayList<>();
    }

    @Override
    public void deleteCart(Long skuId) {
        //1.准备Redis Hash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey =  getCartKey(userId);

        BoundHashOperations<String,String,CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        if(hashOperations.hasKey(skuId.toString())){
            hashOperations.delete(skuId.toString());
        }
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        //1.准备Redis Hash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey =  getCartKey(userId);

        String hashKey = skuId.toString();

        BoundHashOperations<String,String,CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        if(hashOperations.hasKey(hashKey)){
            CartInfo cartInfo = hashOperations.get(hashKey);
            cartInfo.setIsChecked(isChecked);
            hashOperations.put(hashKey, cartInfo);
        }
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        //1.准备Redis Hash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey =  getCartKey(userId);
        //redisTemplate.opsForHash().values()
        BoundHashOperations<String,String,CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);

        if(hashOperations.size()>0){
            List<CartInfo> cartInfoList = hashOperations.values();
            for (CartInfo cartInfo : cartInfoList) {
                cartInfo.setIsChecked(isChecked);
                hashOperations.put(cartInfo.getSkuId().toString(),cartInfo);
            }
        }
    }

    @Override
    public void clearCart() {
        //1.准备Redis Hash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey =  getCartKey(userId);

        if(redisTemplate.hasKey(cartKey)){
            redisTemplate.delete(cartKey);
        }
    }

    @Override
    public Boolean updateCartPrice(Long userId) {
        String cartKey=getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOperations.values();
        if(!CollectionUtils.isEmpty(cartInfoList)){
        for (CartInfo cartInfo : cartInfoList){
            if (cartInfo.getIsChecked().intValue()==1){
             SkuPrice skuPrice=remoteProductService.getSkuPrice(cartInfo.getSkuId(), SecurityConstants.INNER).getData();
             cartInfo.setCartPrice(skuPrice.getSalePrice());
             cartInfo.setSkuPrice(skuPrice.getSalePrice());
             hashOperations.put(cartInfo.getSkuId().toString(),cartInfo);
            }
        }
        }
        return true;
    }

    @Override
    public Boolean deleteCartCheckedList(Long userId) {
        String cartKey=getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOperations.values();
        if(!CollectionUtils.isEmpty(cartInfoList)) {
            for (CartInfo cartInfo : cartInfoList) {
                if (cartInfo.getIsChecked().intValue() == 1) {
                    hashOperations.delete(cartInfo.getSkuId().toString());
                }
            }
        }
        return true;
    }

    @Override
    public List<CartInfo> getCartCheckedList(Long userId) {
        List<CartInfo> checkedCartList = new ArrayList<>();
        //1.准备Redis Hash类型的key
        String cartKey =  getCartKey(userId);
        List<CartInfo> values = redisTemplate.opsForHash().values(cartKey);
        if(!CollectionUtils.isEmpty(values)){
            for (CartInfo cartInfo : values) {

                if(cartInfo.getIsChecked().intValue() == 1){
                    checkedCartList.add(cartInfo);
                }
            }
        }

        return checkedCartList;
    }
}